package com.sdy.hospitalguard.web.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.EncodeUtil;
import com.sdy.hospitalguard.biz.constants.Constants;
import com.sdy.hospitalguard.biz.constants.RedisConstants;
import com.sdy.hospitalguard.biz.model.Manager;
import com.sdy.hospitalguard.biz.service.InpatientAreaService;
import com.sdy.hospitalguard.biz.service.ManagerService;
import com.sdy.hospitalguard.biz.service.RoleService;
import com.sdy.hospitalguard.biz.utils.PassWordUtil;
import com.sdy.hospitalguard.web.vo.WebUserInfoVO;
import com.sdy.hospitalguard.web.websocket.base.BaseWebsocketServer;
import com.sdy.mvc.controller.BaseController;
import com.sdy.redis.service.RedisService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.KeyPair;
import java.util.Base64;
import java.util.Map;

/**
 * Created by zzq on 2019/1/10.
 */
@Slf4j
@RestController
public class IndexController extends BaseController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private InpatientAreaService inpatientAreaService;

    @GetMapping("/publicKey")
    public Response<Object> publicKey(HttpServletRequest request) throws Exception {
        KeyPair keyPair = EncodeUtil.rsaGenKeyPair();
        String publicKeyStr = new String(Base64.getEncoder().encode(keyPair.getPublic().getEncoded()));
        redisService.set(RedisConstants.REDIS_PREFIX + "privateKey_" + getUserId(request), Base64.getEncoder().encode(keyPair.getPrivate().getEncoded()));
        return Response.success(publicKeyStr);
    }

    @GetMapping("/webUserInfo")
    @ApiOperation(value = "获取当前用户基本信息")
    public Response<WebUserInfoVO> webUserInfo(HttpServletRequest request) {
        Integer userId = getUserId(request, Constants.SESSION_WEB_USER_ID);
        Manager manager = managerService.getById(userId);
        if (manager == null) {
            return Response.error();
        }
        // 查询角色
        String roleName = null;
        if (manager.getRoleId() != null) {
            roleName = roleService.getById(manager.getRoleId()).getRoleName();
        }
        // 查询负责病区
        String areaName = null;
        if (manager.getInpatientAreaId() != null) {
            areaName = inpatientAreaService.getById(manager.getInpatientAreaId()).getName();
        }
        String name = manager.getName();
        if (StringUtils.isNotBlank(roleName) && StringUtils.isNotBlank(areaName)) {
            name = areaName + "-" + roleName + "-" + manager.getName();
        } else if (StringUtils.isNotBlank(roleName)) {
            name = roleName + "-" + manager.getName();
        } else if (StringUtils.isNotBlank(areaName)) {
            name = areaName + "-" + manager.getName();
        }
        WebUserInfoVO userInfoVO = new WebUserInfoVO();
        userInfoVO.setName(name).setRoleId(manager.getRoleId());
        return Response.success(userInfoVO);
    }

    @GetMapping("/createWsConnectionId")
    public Response<Object> createConnectionId(HttpServletRequest request) {
        String connId = BaseWebsocketServer.createConnectionId(redisService, getUserId(request));
        if (connId == null) {
            return Response.error("用户未登录，创建连接ID失败");
        }
        return Response.success(connId);
    }

    @PostMapping("/modifyPassword")
    @ApiOperation(value = "修改密码")
    public Response<Boolean> modifyPassword(HttpServletRequest request, @RequestBody Map<String, String> params) throws Exception {
        String passwordOld = params.get("passwordOld");
        String passwordNew = params.get("password");
        Integer userId = getUserId(request);
        Assert.isNull(userId, "用户id不能为空");
        Assert.isBlank(passwordNew, "新密码不能为空");
        Manager user = managerService.getById(userId);
        Assert.isTrue(!PassWordUtil.loginVerify(passwordOld, user.getPassword()), "密码错误");
        boolean update = managerService.lambdaUpdate().eq(Manager::getId, userId)
                .set(Manager::getPassword, PassWordUtil.registerEncryption(passwordNew)).update();
        Assert.notTrue(update, "修改失败!");
        return Response.success(update);
    }

}
